# -*- coding: utf-8 -*-

import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "重大疾病保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year":["0-4","5-15","16-25","26-30","31-35","36-40","41-45"],
            #性别
            "gender":["M","F"],
            #保障期限
            "expire":["1年"],
            #保额
            "majorDisease":["30000","50000","80000","100000","200000","300000"],
            #缴费类型
            "payType":["年交"]
        }
        for v in product(plan["year"],plan["gender"],plan["expire"],plan["majorDisease"],plan["payType"]):
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(
                v[0],v[1],v[2],v[3],v[4]
            ))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format(
                v[0],v[1],v[2],v[3],v[4]
            ))
    #执行爬虫
    def requestJson(self,dt=None):
        if dt["year"] == "0-4":
            age = "6"
        elif dt["year"] == "5-15":
            age = "7"
        elif dt["year"] == "16-25":
            age = "1"
        elif dt["year"] == "26-30":
            age = "2"
        elif dt["year"] == "31-35":
            age = "3"
        elif dt["year"] == "36-40":
            age = "4"
        else:
            age = "5"
        if dt["majorDisease"] == "30000":
            suitId = "5933"
            insuranceId = "24242"
        elif dt["majorDisease"] == "50000":
            suitId = "5934"
            insuranceId = "24243"
        elif dt["majorDisease"] == "80000":
            suitId = "5935"
            insuranceId = "24244"
        elif dt["majorDisease"] == "100000":
            suitId = "5936"
            insuranceId = "24245"
        elif dt["majorDisease"] == "200000":
            suitId = "5937"
            insuranceId = "24246"
        else:
            suitId = "5938"
            insuranceId = "24247"

        data = {

            "insuranceid_"+insuranceId+"_保险金额": dt["majorDisease"],
            "suiteId": suitId,
            "period": "365",
            "sex": "1" if dt["gender"] == "M" else "0",
            "age": age,
            "amount":"",
            "personCount": "1",
            "backInsuranceCount":"",
            "youngAccident": "majorAccident"
        }

        payload = urlencode( data )

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)


        if r.status_code == 200 and "重大疾病保险" in r.text:
            price = Helper.decimalParse( r.json()["totalPrice"] )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品数据失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
